'use strict';

const uniID = require('uni-id-common');
const Buffer = require('buffer').Buffer;

exports.main = async (event, context) => {
  // 获取用户 openid
  let openid;
  let avatar, nickname, gender, skillLevel;
  
  // 如果是HTTP请求，需要从body中解析参数
  if (event.body) {
    try {
      const bodyData = JSON.parse(event.body);
      openid = bodyData.openid;
      avatar = bodyData.avatar || bodyData.avatarData; // 优先使用avatar字段
      nickname = bodyData.nickname;
      gender = bodyData.gender;
      skillLevel = bodyData.skillLevel;
    } catch (error) {
      console.error('解析请求体失败:', error);
      return {
        code: 400,
        message: '请求格式错误'
      };
    }
  } else {
    // 如果是云函数调用，直接从event中获取
    openid = event.openid;
    avatar = event.avatar || event.avatarData; // 优先使用avatar字段
    nickname = event.nickname;
    gender = event.gender;
    skillLevel = event.skillLevel;
  }
  
  // 参数校验
  if (!openid) {
    return {
      code: 400,
      message: '缺少 openid 参数'
    };
  }
  
  try {
    console.log('Received openid:', openid);
    // 如果有头像，直接使用base64格式
    let avatarData = '';
    if (avatar) {
      // 直接使用base64格式的头像数据
      // 如果不是以data:image开头，添加base64前缀
      if (avatar.startsWith('data:image')) {
        avatarData = avatar;
      } else {
        avatarData = `data:image/jpeg;base64,${avatar}`;
      }
    }
    
    // 构造更新数据
    const updateData = {};
    if (nickname) updateData.nickname = nickname;
    if (gender !== undefined) updateData.gender = gender;
    if (skillLevel) updateData.skill_level = skillLevel;
    if (avatarData) updateData.avatar = avatarData;
    
    // 更新用户信息
    // 注意：uni-id-common 不支持直接通过 openid 更新用户
    // 我们需要先通过 openid 查找用户 uid
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    console.log('Querying user with wx_openid:', openid);
    const userRecord = await usersCollection.where({
      'wx_openid.mp-weixin': openid
    }).get();
    console.log('User query result:', userRecord);
    
    if (userRecord.data && userRecord.data.length > 0) {
      const updateResult = await usersCollection.doc(userRecord.data[0]._id).update(updateData);
      console.log('updateResult',updateResult);
      
      if (updateResult.updated > 0) {
        return {
          code: 0,
          message: '用户信息更新成功'
        };
      } else {
        return {
          code: 500,
          message: '请修改信息后再提交'
        };
      }
    } else {
      return {
        code: 404,
        message: '未找到用户'
      };
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    return {
      code: 500,
      message: '服务器内部错误'
    };
  }
};